package com.zq.ht.common.util;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

public class PageUtil {
	
	//总记录数
	protected int totalRows = 0;
			
	//起始记录数
	protected int rowStart;
		    
	//每页显示记录条数
	protected int rowCount = 0;
			
	//默认每页显示记录条数
	protected int DEFAULT_ROWS_DISPLAYED = 10;
			
	//起始页
	protected int page;
			
	//总页数
	protected int pageCount;
	
	//记录
	protected List results;

	public PageUtil() {}

	public PageUtil(HttpServletRequest request) throws Exception {
		String currPage = request.getParameter("page");
		if (currPage == null || currPage.equals("")) {
			currPage = "1";
		}
		page = Integer.parseInt(currPage);
		if (page <= 0) {
			page = 1;
		}
		
		String rows = request.getParameter("rows");
		if (rows == null || rows.equals("")) {
			rows = "0";
		}
		rowCount = Integer.parseInt(rows);
		if (rowCount <= 0) {
			rowCount = DEFAULT_ROWS_DISPLAYED;
		}
	        
		rowStart = (page - 1) * rowCount;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public int getTotalRows() {
		return totalRows;
	}
	
	public List getResults() {
		return results;
	}

	public void setResults(List results) {
		this.results = results;
	}

	public void setTotalRows(int totalRows) {
		this.totalRows = totalRows;
		int n = this.totalRows;
		if (n <= 0) {
			pageCount = 0;
		}
		pageCount = n / rowCount;
		if (n % rowCount > 0) {
			pageCount++;
		}
		if (pageCount <= 0) {
			pageCount = 0;
		}
		page = this.rowStart / rowCount + 1;
		if(page > pageCount){
			page = pageCount;
		}
		if(page == 0 && pageCount > 0){
			page = 1;
		}
	}
		
	public void setRowCount(int rowCount) {
		this.rowCount = rowCount;
		this.rowStart = (this.page - 1) * this.rowCount;
	}
		
	public int getRowCount() {
		return rowCount;
	}

	public int getRowStart() {
		if (totalRows <= 0 || rowCount <= 0) {
			rowStart = 0;
		} else if (rowStart >= totalRows) {
			int pages = totalRows / rowCount;
			if ((totalRows % rowCount) == 0) {
				pages--;
			}
			rowStart = pages * rowCount;
		}
		if (rowStart <= 0) {
			rowStart = 0;
		}
		return rowStart;
	}
	
}
